import * as path from 'path';
import * as XLSX from 'xlsx';

class Xlsx<Header = { [x: string]: string }, CoreData = Record<keyof Header, string>> {
  header: Header;

  coreData: CoreData[];

  constructor(header: Header) {
    this.header = header;
  }

  public setData(data: CoreData[]) {
    this.coreData = data;
  }

  public generateExcelFile(filename: string, resolvePath?: string) {
    const realResolvePath = resolvePath
      ?? path.resolve(__dirname, `../public/xlsx/${filename}`);
    const { header, coreData } = this;

    const keyOrder: string[] = [];

    const xlsxData: string[][] = [[]];

    // 获取顺序
    for (const headerKey in header) {
      if ({}.hasOwnProperty.call(header, headerKey)) {
        keyOrder.push(headerKey);
      }
    }

    for (const key of keyOrder) {
      xlsxData[0].push(header[key]);
    }

    coreData.forEach((coreDataItem) => {
      const xlsxDataItem: string[] = [];

      for (const key of keyOrder) {
        xlsxDataItem.push(coreDataItem[key]);
      }

      xlsxData.push(xlsxDataItem);
    });

    // 创建 workbook 对象
    const wb = XLSX.utils.book_new();
    // 将srcData转换为worksheet
    const ws = XLSX.utils.aoa_to_sheet(xlsxData);
    // worksheet 加入workbook
    XLSX.utils.book_append_sheet(wb, ws, '1');
    // 导出
    XLSX.writeFile(wb, realResolvePath);

    return realResolvePath;
  }
}

export default Xlsx;
